﻿using System;
using Newtonsoft.Json;

namespace Ecobee.Net
{
	public class GeoCodeConverter : JsonConverter
	{
		public override bool CanConvert(Type objectType)
		{
			bool returnValue = false;


			return returnValue;
		}

		public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
		{
			object returnValue = null;

			if (objectType == typeof(GeoCode))
			{
				string value = (string)reader.Value;
				int pos = value.IndexOf(",");

				if (pos > -1)
				{
					string latValue = value.Substring(0, pos - 1);
					((GeoCode)existingValue).Latitude = Convert.ToDouble(latValue);

					string longValue = value.Substring(pos + 1, value.Length - pos - 1);
					((GeoCode)existingValue).Longitude = Convert.ToDouble(longValue);
				}

				returnValue = existingValue;
			}

			return returnValue;
		}

		public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
		{
			GeoCode geo = value as GeoCode;

			if (geo != null)
			{
				writer.WriteValue(string.Format("{0},{1}", geo.Latitude, geo.Longitude));
			}
			else
			{
				writer.WriteValue("0,0");
			}
		}
	}
}
